import axios, { AxiosInstance } from 'axios'
import { GCRequestInterceptors, GCRequestConfig } from './types'

class GCRequest {
  instence: AxiosInstance
  interceptors?: GCRequestInterceptors

  constructor(config: GCRequestConfig) {
    this.instence = axios.create(config)
    this.interceptors = config.interceptors

    // 示例的拦截器
    this.instence.interceptors.request.use(
      this.interceptors?.requestInterceptors,
      this.interceptors?.requestInterceptorsCatch
    )
    this.instence.interceptors.response.use(
      this.interceptors?.responseInterceptors,
      this.interceptors?.responseInterceptorsCatch
    )

    // 全部的拦截器
    this.instence.interceptors.request.use(
      (config: any) => {
        const token = localStorage.getItem('token')
        config.headers.Authorization = `Bearer ${token}`
        return config
      },
      (err) => {
        console.log(err)
      }
    )
    this.instence.interceptors.response.use(
      (res) => {
        return res.data
      },
      (err) => {
        console.log(err)
      }
    )
  }

  request<T = any>(config: GCRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config)
      }
      this.instence
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptors) {
            res = config.interceptors.responseInterceptors(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  get<T = any>(config: GCRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }
  post<T = any>(config: GCRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }
  patch<T = any>(config: GCRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'PATCH' })
  }
  delete<T = any>(config: GCRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }
}

export default GCRequest
